package database;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;

import main.Terminal;
import model.Movie;

public class DBMovie {

	
	private final String id ="ID";
	private final String price = "Price";
	private final String length = "Length";
	private final String title = "Title";
	private final String commercialTime = "CommercialTime";
	private final String description = "Description";
	private final String is3d = "Is3D";
	private final String selectAll = String.format("SELECT %s, %s, %s, %s, %s, %s, %s FROM Movie", id, price, length, title, commercialTime, description, is3d);
	
	private DBConnection con;
	/**
	 * @param Jan
	 */
	public DBMovie()
	{
		con = DBConnection.getInstance();
	}
	
	public Movie getMovie(int id)
	{
		String newID = Integer.toString(id);
		String query = selectWhere("ID", newID); 
		ResultSet resSet = con.executeResSet(query);
		Movie m = null;
		
		try {
			resSet.next();
			m = buildMovie(resSet);
			resSet.getStatement().close();
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return m;
	}
	
	public ArrayList<Movie> getMoviesByName(String name)
	{
		ArrayList<Movie> mList = new ArrayList<Movie>();
		
		try {
			ResultSet resSet = con.executeResSet(selectWhereName(name));
			while(resSet.next()) {
				Movie m = buildMovie(resSet);
				if(m != null) {
					mList.add(m);
				}
			}
			resSet.getStatement().close();
		}
		catch(SQLException sE) {
			Terminal.say("Stack trace: ", sE);
		}
		
		return mList;
	}
	
	private Movie buildMovie(ResultSet resSet)
	{
		Movie movie = null;
		try {
//			while(resSet.next()) {
				int iD = resSet.getInt(id);
				double price = resSet.getDouble(this.price);
				int length = resSet.getInt(this.length);
				String title = resSet.getString(this.title);
				int commercialTime = resSet.getInt(this.commercialTime);
				String description = resSet.getString(this.description);
				boolean is3d = resSet.getBoolean(this.is3d);
				movie = new Movie(iD, price, length, title, commercialTime, description, is3d);
//			}
//			resSet.getStatement().close();
		}
		catch(SQLException e)
		{
			Terminal.say("test", e);
		}
		catch (Exception e)
		{
			Terminal.say("An error occured building an Movie object", e);
		}
		return movie;
	}
	
	private String selectWhere(String condition, String argument)
	{
		return selectAll + " WHERE " + condition + " = " + argument;
	}
	
	private String selectWhereName(String argument)
	{
		return selectAll + " WHERE Title" + " like '%" + argument + "%'";
	}
	
}
